﻿using Autofac;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCS_Entity.Dto.AutoEquipmentDto;
using WCS_Entity.Model;
using WCS_Service.DomianService.Interface;
using WCS_Utility.Enums;

namespace WCS_Service.DomianService
{
    /// <summary>
    /// 通信服务管理类
    /// </summary>
    public class ComControl : IComControl
    {
        private readonly IComponentContext _componentContext;

        private ConcurrentBag<IComBaseDomainManage> autoEquipmentComServices { get; set; } = new ConcurrentBag<IComBaseDomainManage>();

        public ComControl(IComponentContext componentContext)
        {
            _componentContext = componentContext;
        }
        /// <summary>
        /// 服务创建检查
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> ServiceCreateCheckAsync(int id)
        {
            var service = autoEquipmentComServices.Where(a => a.autoEquipmentId == id)?.ToList();
            if (service is null || !service.Any())
            { 
                return true;
            }
            return false;
        }
        /// <summary>
        /// 创建通信服务
        /// </summary>
        /// <param name="comPara"></param>
        /// <returns></returns>
        public async Task<bool> CreateComServiceAsync(ComInitParaModel comPara)
        {
            try
            {
                var service = _componentContext.ResolveKeyed<IComBaseDomainManage>(comPara.comType);
                service.serviceName = comPara.serviceName;
                service.autoEquipmentId = comPara.AutoEquipmentId;
                var comModel = new TcpComParaModel() { ip = comPara.ip , port = comPara.port };
                service.comPara = JsonConvert.SerializeObject(comModel); 
                service.protocolPara = comPara.protocolMsgList;
                if (!await service.InitService())
                {
                    return false;  
                }
                autoEquipmentComServices.Add(service);
                return true;
            }
            catch (Exception ex) 
            {
                Log.Error($"创建通信服务异常{ex.Message}");
                return false;
            }
        }

        public async Task<List<RunAutoEquipmentInfoDto>> GetAllRunServiceInfoAsync()
        {
            List<RunAutoEquipmentInfoDto> result = new List<RunAutoEquipmentInfoDto>();
            List<Task<RunAutoEquipmentInfoDto>> runInfoList = new List<Task<RunAutoEquipmentInfoDto>>();
            foreach (var item in autoEquipmentComServices)
            {
                runInfoList.Add(GetRunServiceInfoAsync(item));
            }
            await Task.WhenAll(runInfoList);
            result = runInfoList.Select(r => r.Result).ToList();
            return result;
        }

        #region private
        private async Task<RunAutoEquipmentInfoDto> GetRunServiceInfoAsync(IComBaseDomainManage service)
        {
            RunAutoEquipmentInfoDto result = new RunAutoEquipmentInfoDto();
            await Task.Run(() => 
            {
                result.name = service.serviceName;
                result.autoEquipmentId = service.autoEquipmentId;
                result.serviceIp = service.comPara;
                result.protocolInfo = new Dictionary<string, ProtocolModel>(service.protocolMsgList);
            });
            return result;
        }
        #endregion
    }
}
